import json
import logging
import traceback

from websocket import WebSocketApp

from model.CommandEnum import CommandEnum
from model.WebsocketClientVO import WebsocketClientVO
from service.ClashService import ClashService


class CommandDispatcherService(object):

    def __init__(self, info: WebsocketClientVO):
        self.clashService = ClashService(info)

    def dispatch(self, ws:WebSocketApp, message):
        data = json.loads(message)
        commandStr = str(data['command']).lower()
        resMessage = ''
        success = True
        resData = ''
        reqParam = data['data']
        try:
            resData = self.doDispatch(commandStr, ws, reqParam)
        except Exception as e:
            traceback.print_exc()
            logging.exception(message)
            resMessage = e.__str__()
            success = False
        res = {
            'data': resData,
            'message': resMessage,
            'success': success
        }
        ws.send(json.dumps(res))

    def doDispatch(self, commandStr, ws, data):
        if commandStr == CommandEnum.CLASH_FETCH.value: return self.clashService.fetch(ws, data)
        if commandStr == CommandEnum.CLASH_CHANGE_PROXY.value: return self.clashService.changeCurrentProxy(ws, data)
        if commandStr == CommandEnum.CLASH_CURRENT_PROXY.value: return self.clashService.getCurrentProxy(ws, data)